<?php

namespace App\Http\Controllers\Admin;

use App\Models\Category;
use App\Models\CategoryUser;
use App\Models\GoodsRate;
use App\Models\Source;
use App\Services\CommonService;
use Illuminate\Http\Request;

//品类审核
class CategoryExamineController extends BaseController
{
    //品类审核列表
    public function categoryExamineList(Request $request)
    {
        $input = $request->input();
        $where = [];
        $where[] = ['c.enabled', Category::CATEGORY_STATUS_DISPLAY];
        $where[] = ['c.is_delete', Category::CATEGORY_NOT_DELETE];
        $where[] = ['cu.status', CategoryUser::CATEGORY_USER_STATUS_ENABLE];
        $where[] = ['cu.is_delete', CategoryUser::CATEGORY_USER_NOT_DELETE];
        if (!empty($input['name'])) {
            $where[] = ['c.name', 'like', '%' . trim($input['name']) . '%'];
        }
        if (!empty($input['shopname'])) {
            $where[] = ['su.shopname', 'like', '%' . trim($input['shopname']) . '%'];
        }
        if (!empty($input['create_time'])) {
            $time = searchTime($input['create_time']);
            $where[] = ['cu.create_time', '>=', strtotime($time['begin_time'])];
            $where[] = ['cu.create_time', '<', strtotime($time['end_time'])];
        }
        //审核状态：1已审核 2待审核 3拒绝审核
        switch ($input['ischeck']) {
            case '1'://已审核
                $check_where[] = ['cu.ischeck', CategoryUser::CATEGORY_USER_IS_CHECK];
                break;
            case '2'://待审核
                $check_where[] = ['cu.ischeck', CategoryUser::CATEGORY_USER_NOT_CHECK];
                break;
            case '3'://拒绝审核
                $check_where[] = ['cu.ischeck', CategoryUser::CATEGORY_USER_REFUSE_CHECK];
                break;

            default://全部
                $check_where = [];
                break;
        }
        $page = $input['page'] ? $input['page'] : 1;
        $pageSize = $input['pageSize'] ? $input['pageSize'] : CommonService::PAGESIZE;
        $data = CategoryUser::GetCategoryExamineList($pageSize, $where, $check_where);
        $data = formatPage($data);
        $info = $data['data'];
        foreach ($info as $k => $v) {
            $info[$k]['create_time'] = !empty($v['create_time']) ? dateFormat($v['create_time']) : '';
            $info[$k]['category_name'] = $v['name'];
            $goodsRate = GoodsRate::GetGoodsRate(array('gr.member_id' => $v['member_id'], 'gr.category_id' => $v['category_id'], 'gr.is_delete' => GoodsRate::GOODS_RATE_NOT_DELETE)); //商品费率
            $category_rate = '';
            foreach ($goodsRate as $key => $val) {
                $category_rate .= $val['source_name'] . '(' . $val['fixed_cost'] . '元 + ' . $val['goods_rate'] . '%),';
            }
            $info[$k]['category_rate'] = rtrim($category_rate, ',');
        }
        $data['data'] = $info;
        //计算数量
        unset($check_where);
        $data['count']['check_total'] = CategoryUser::GetCategoryExamineIscheckCount($where, []);
        unset($check_where);
        $check_where[] = ['cu.ischeck', CategoryUser::CATEGORY_USER_IS_CHECK];
        $data['count']['ischeck_total'] = CategoryUser::GetCategoryExamineIscheckCount($where, $check_where);
        unset($check_where);
        $check_where[] = ['cu.ischeck', CategoryUser::CATEGORY_USER_NOT_CHECK];
        $data['count']['notcheck_total'] = CategoryUser::GetCategoryExamineIscheckCount($where, $check_where);
        unset($check_where);
        $check_where[] = ['cu.ischeck', CategoryUser::CATEGORY_USER_REFUSE_CHECK];
        $data['count']['refusecheck_total'] = CategoryUser::GetCategoryExamineIscheckCount($where, $check_where);
        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '获取成功', $data);
    }

    //根据idStr获取商户分类信息 http://shop.cn/Admin/CategoryExamine/categoryUserByIdStr?idStr=
    public function categoryUserByIdStr(Request $request)
    {
        $input = $request->input();
        if (empty($input['idStr'])) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '商户分类id为空');
        }
        $idArr = explode(',', $input['idStr']);
        $select = array('cu.id', 'cu.member_id', 'cu.category_id', 'cu.member_id', 'c.parentid', 'c.name', 'su.shopname');
        $categoryUser = CategoryUser::from('sp_category_user_2 as cu')
            ->leftjoin('sp_category as c', 'c.id', 'cu.category_id')
            ->leftjoin('sp_shop_user_2 as su', 'su.member_id', 'cu.member_id')
            ->select($select)
            ->whereIn('cu.id', $idArr)
            ->where(array(
                'c.enabled' => Category::CATEGORY_STATUS_DISPLAY,
                'c.is_delete' => Category::CATEGORY_NOT_DELETE,
                'cu.status' => CategoryUser::CATEGORY_USER_STATUS_ENABLE,
                'cu.is_delete' => CategoryUser::CATEGORY_USER_NOT_DELETE
            ))
            ->get();
        $categoryUser = $categoryUser ? $categoryUser->toArray() : [];
        foreach ($categoryUser as $k => $v) {
            $parent_category = Category::GetOne($v['parentid']);
            $categoryUser[$k]['category_name'] = $parent_category['name'] . '->' . $v['name'];
        }
        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '获取成功', $categoryUser);
    }

    //根据id编辑商户分类信息的审核状态(通过、拒绝)
    public function editCategoryUserIscheck(Request $request)
    {
        $is_preposition= $request->input('is_preposition',0); //订单编号
        $post_deduction= $request->input('post_deduction',0); //订单编号

        $input = $request->input();
        if (empty($input['idStr'])) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '商户分类id为空');
        }
        if (empty($input['ischeck'])) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '审核状态为空');
        }
        $idArr = explode(',', $input['idStr']);
        $categoryUser = CategoryUser::whereIn('id', $idArr)->where([['ischeck', '!=', CategoryUser::CATEGORY_USER_NOT_CHECK], ['status', CategoryUser::CATEGORY_USER_STATUS_ENABLE]])->get(); //审核状态：1已审核 2待审核 3拒绝审核
        $categoryUser = $categoryUser ? $categoryUser->toArray() : [];
        if (!empty($categoryUser)) {
            $neq2IdStr = '';
            foreach ($categoryUser as $k => $v) {
                $neq2IdStr .= $v['id'] . ',';
            }
            $neq2IdStr = rtrim($neq2IdStr, ',');
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, 'ID为' . $neq2IdStr . '的当前审核状态不是待审核');
        } else {
            if ($input['checkType'] == 'pass') { //通过
                return $this->batchSetRate($input['goods_rate'], $input['rate_list'], $idArr, $input['ischeck'],$is_preposition,$post_deduction);
            } elseif ($input['checkType'] == 'refuse') { //拒绝
                if ($input['check_refuse_type'] == 1) { //审核拒绝类型：1营业执照经营范围不包含该品类 2其他原因
                    CategoryUser::whereIn('id', $idArr)->update(array('ischeck' => $input['ischeck'],'is_preposition'=>$is_preposition?1:0, 'check_refuse_type' => $input['check_refuse_type'], 'update_time' => date('Y-m-d H:i:s')));
                } else {
                    if (empty($input['check_refuse_reason'])) {
                        return ReturnMsg(CommonService::HTTP_CODE_FAIL, '拒绝原因为空');
                    }
                    CategoryUser::whereIn('id', $idArr)->update(array('ischeck' => $input['ischeck'], 'check_refuse_type' => $input['check_refuse_type'], 'check_refuse_reason' => $input['check_refuse_reason'], 'update_time' => date('Y-m-d H:i:s')));
                }
                return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '拒绝成功');
            }
        }
    }

    //批量设置费率并修改审核状态为通过(审核通过前必须设置费率)
    private function batchSetRate($goods_rate, $rate_list, $idArr, $ischeck)
    {
        if (empty($rate_list)) {
            echo ReturnMsg(CommonService::HTTP_CODE_FAIL, '数据为空,请设置费率');
        }
        $source_ids = array_column($rate_list, 'source_id');
        if (count($source_ids) != count(array_unique($source_ids))) {
            echo ReturnMsg(CommonService::HTTP_CODE_FAIL, '订单来源不能设置重复,请重新设置');
        }
        foreach ($goods_rate as $k1 => $v1) {
            foreach ($rate_list as $k2 => $v2) {
                $getOneGoodsRate = GoodsRate::GetOneGoodsRate(array('member_id' => $v1['member_id'], 'category_id' => $v1['category_id'], 'source_id' => $v2['source_id']));
                $data = array(
                    'member_id' => $v1['member_id'], //member_id
                    'category_id' => $v1['category_id'], //category_id
                    'is_preposition'=>$v2['is_preposition']?1:0,
                    'source_id' => $v2['source_id'], //来源id
                    'fixed_cost' => $v2['smartcontract'] + $v2['realname'] + $v2['risk'], //固定费用(单位元)=合同费用+实名认证费用+风控费用
                    'goods_rate' => $v2['platform'] + $v2['withhold'] + $v2['file'] + $v2['financing'], //店铺费率%=平台手续费%+代扣手续费%+存证手续费%+融资手续费%
                    'smartcontract' => $v2['smartcontract'], //合同费用  单位元
                    'realname' => $v2['realname'], //实名认证费用  单位元
                    'risk' => $v2['risk'], //风控费用  单位元
                    'platform' => $v2['platform'], //平台手续费%
                    'withhold' => $v2['withhold'], //代扣手续费%
                    'file' => $v2['file'], //存证手续费%
                    'financing' => $v2['financing'], //融资手续费%
                    'is_delete' => $v2['is_delete'], //是否删除 0未删除 1已删除
                    'post_deduction'=>$v2['post_deduction'],
                );
                if ($getOneGoodsRate) {
                    $data['update_time'] = date('Y-m-d H:i:s');
                    GoodsRate::editData(array('id' => $getOneGoodsRate['id'], 'member_id' => $v1['member_id'], 'category_id' => $v1['category_id']), $data);
                } else {
                    $data['create_time'] = date('Y-m-d H:i:s');
                    GoodsRate::addData($data);
                }
            }
        }
        CategoryUser::whereIn('id', $idArr)->update(array('ischeck' => $ischeck, 'update_time' => date('Y-m-d H:i:s')));
        echo ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '审核成功');
    }

    //根据id删除商户分类信息POST http://shop.cn/Admin/CategoryExamine/delCategoryUser     idStr=
    public function delCategoryUser(Request $request)
    {
        $input = $request->input();
        if (empty($input['idStr'])) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '商户分类id为空');
        }
        $idArr = explode(',', $input['idStr']);
        CategoryUser::whereIn('id', $idArr)->update(array('is_delete' => CategoryUser::CATEGORY_USER_IS_DELETE, 'update_time' => date('Y-m-d H:i:s')));
        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '删除成功');
    }

    //根据member_id、category_id获取订单来源和费率信息 http://shop.cn/Admin/CategoryExamine/getSourceAndRate?member_id=&category_id=
    public function getSourceAndRate(Request $request)
    {
        $input = $request->input();
        if (empty($input['member_id'])) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, 'member_id为空');
        }
        if (empty($input['category_id'])) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, 'category_id为空');
        }
        $goodsRate = GoodsRate::GetGoodsRate(array('gr.member_id' => $input['member_id'], 'gr.category_id' => $input['category_id'], 'gr.is_delete' => GoodsRate::GOODS_RATE_NOT_DELETE)); //商品费率
        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '获取成功', $goodsRate);
    }

    //根据member_id、category_id获取订单来源信息 http://shop.cn/Admin/CategoryExamine/getSource
    public function getSource()
    {
        $source = Source::GetSource(array('status' => Source::SOURCE_STATUS_ENABLE));
        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '获取成功', $source);
    }

    //设置费率POST
    public function setRate(Request $request)
    {
        $is_preposition= $request->input('is_preposition',0); //订单编号
        $input = $request->input();
        if (empty($input['member_id'])) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, 'member_id为空');
        }
        if (empty($input['category_id'])) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, 'category_id为空');
        }
        if (empty($input['rate_list'])) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '数据为空,请设置费率');
        }
        $rate_list = $input['rate_list'];
        $source_ids = array_column($rate_list, 'source_id');
        if (count($source_ids) != count(array_unique($source_ids))) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '订单来源不能设置重复,请重新设置');
        }
        // dd($rate_list);
        foreach ($rate_list as $k => $v) {
            if (empty($v['source_id'])) {
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '请设置订单来源');
            }
            if (empty($v['smartcontract'])) {
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '请设置合同费用');
            } else {
                if (!is_numeric($v['smartcontract'])) {
                    return ReturnMsg(CommonService::HTTP_CODE_FAIL, '合同费用只能是数字');
                } elseif (strpos($v['smartcontract'], '-') !== false) {
                    return ReturnMsg(CommonService::HTTP_CODE_FAIL, '合同费用不能为负数');
                }
            }
            if (empty($v['realname'])) {
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '请设置实名认证费用');
            } else {
                if (!is_numeric($v['realname'])) {
                    return ReturnMsg(CommonService::HTTP_CODE_FAIL, '实名认证费用只能是数字');
                } elseif (strpos($v['realname'], '-') !== false) {
                    return ReturnMsg(CommonService::HTTP_CODE_FAIL, '实名认证费用不能为负数');
                }
            }
            if (empty($v['risk'])) {
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '请设置风控费用');
            } else {
                if (!is_numeric($v['risk'])) {
                    return ReturnMsg(CommonService::HTTP_CODE_FAIL, '风控费用只能是数字');
                } elseif (strpos($v['risk'], '-') !== false) {
                    return ReturnMsg(CommonService::HTTP_CODE_FAIL, '风控费用不能为负数');
                }
            }
            if (empty($v['platform'])) {
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '请设置平台手续费');
            } else {
                if (!is_numeric($v['platform'])) {
                    return ReturnMsg(CommonService::HTTP_CODE_FAIL, '平台手续费只能是数字');
                } elseif (strpos($v['platform'], '-') !== false) {
                    return ReturnMsg(CommonService::HTTP_CODE_FAIL, '平台手续费不能为负数');
                }
            }
            if (empty($v['withhold'])) {
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '请设置代扣手续费');
            } else {
                if (!is_numeric($v['withhold'])) {
                    return ReturnMsg(CommonService::HTTP_CODE_FAIL, '代扣手续费只能是数字');
                } elseif (strpos($v['withhold'], '-') !== false) {
                    return ReturnMsg(CommonService::HTTP_CODE_FAIL, '代扣手续费不能为负数');
                }
            }
            if (empty($v['file'])) {
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '请设置存证手续费');
            } else {
                if (!is_numeric($v['file'])) {
                    return ReturnMsg(CommonService::HTTP_CODE_FAIL, '存证手续费只能是数字');
                } elseif (strpos($v['file'], '-') !== false) {
                    return ReturnMsg(CommonService::HTTP_CODE_FAIL, '存证手续费不能为负数');
                }
            }
            if (empty($v['financing'])) {
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '请设置融资手续费');
            } else {
                if (!is_numeric($v['financing'])) {
                    return ReturnMsg(CommonService::HTTP_CODE_FAIL, '融资手续费只能是数字');
                } elseif (strpos($v['financing'], '-') !== false) {
                    return ReturnMsg(CommonService::HTTP_CODE_FAIL, '融资手续费不能为负数');
                }
            }
            $data = array(
                'member_id' => $input['member_id'], //member_id
                'category_id' => $input['category_id'], //category_id
                'is_preposition'=>$v['is_preposition']?'1':0,//是否前置
                'post_deduction'=>$v['post_deduction'],//前置的同时，后置扣款手续费%
                'source_id' => $v['source_id'], //来源id
                'fixed_cost' => $v['smartcontract'] + $v['realname'] + $v['risk'], //固定费用(单位元)=合同费用+实名认证费用+风控费用
                'goods_rate' => $v['platform'] + $v['withhold'] + $v['file'] + $v['financing'], //店铺费率%=平台手续费%+代扣手续费%+存证手续费%+融资手续费%
                'smartcontract' => $v['smartcontract'], //合同费用  单位元
                'realname' => $v['realname'], //实名认证费用  单位元
                'risk' => $v['risk'], //风控费用  单位元
                'platform' => $v['platform'], //平台手续费%
                'withhold' => $v['withhold'], //代扣手续费%
                'file' => $v['file'], //存证手续费%
                'financing' => $v['financing'], //融资手续费%
                'is_delete' => $v['is_delete'], //是否删除 0未删除 1已删除
            );

            if (empty($v['id'])) { //添加
                $getOneGoodsRate = GoodsRate::GetOneGoodsRate(array('member_id' => $input['member_id'], 'category_id' => $input['category_id'], 'source_id' => $v['source_id']));
                if ($getOneGoodsRate) {
                    $data['update_time'] = date('Y-m-d H:i:s');
                    GoodsRate::editData(array('id' => $getOneGoodsRate['id'], 'member_id' => $input['member_id'], 'category_id' => $input['category_id']), $data);
                } else {
                    $data['create_time'] = date('Y-m-d H:i:s');
                    GoodsRate::addData($data);
                }
            } else { //修改
                $data['update_time'] = date('Y-m-d H:i:s');
                GoodsRate::editData(array('id' => $v['id'], 'member_id' => $input['member_id'], 'category_id' => $input['category_id']), $data);
            }
        }

        CategoryUser::where(array('member_id' => $input['member_id'], 'category_id' => $input['category_id']))->update(array('is_preposition'=>$is_preposition?1:0));
        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '设置成功');
    }

}
